package com.example.thread;

import com.zaxxer.hikari.HikariDataSource;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class InsertTask implements Runnable{
    private final List<String> msg;
    private AtomicInteger num;
    private long begin;
    private final HikariDataSource hikariDataSource;

    public InsertTask(List<String> msg, AtomicInteger num, long begin, HikariDataSource hikariDataSource) {
        this.msg = msg;
        this.num = num;
        this.begin = begin;
        this.hikariDataSource = hikariDataSource;
    }

    @Override
    public void run() {
        long start = System.currentTimeMillis();
        Connection connection=null;
        try{
            connection = hikariDataSource.getConnection();
            connection.setAutoCommit(false);
            Statement statement = connection.createStatement();
            StringBuilder sql = new StringBuilder("INSERT ALL ");
            for (int i = 0; i < msg.size(); i++) {
                String s=msg.get(i);
                s ="'"+s.replace(",", "','")+"'";
                sql.append("INTO T_BOND_BASIS_INFO VALUES (")
                        .append(s)
                        .append(") ");
                if ((i+1)%50==0 || i-1==msg.size()){
                    sql.append("SELECT 1 from DUAL");
                    String str = sql.toString();
                    statement.executeUpdate(str);
                    sql = new StringBuilder("INSERT ALL ");
                }
            }
            connection.commit();
            long end = System.currentTimeMillis();
            System.out.println("总耗时:"+(end-begin)/1000+"s,单次耗时:"+(end-start)+"ms;批次:"+num.getAndIncrement()*200);
            msg.clear();
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            if (connection!=null){
                hikariDataSource.evictConnection(connection);
            }
        }
    }
}
